package com.carp.config.interceptorConfig;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import com.carp.entity.CarpUser;
import com.carp.exception.ServiceException;
import com.carp.mapper.CarpUserMapper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private CarpUserMapper workUserMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的token
        String token = request.getHeader("token");

        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //执行认证
        if (token == null || token.equals("")){
            throw new ServiceException(401,"无token,请重新登录!");
        }
        //验证token中的phone,并获取phone
        String userPhone;
        try {
            userPhone = JWT.decode(token).getAudience().get(0);
        }catch (Exception e){
            throw new ServiceException(401,"token 验证失败!");
        }

        //数据查找用户
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone",userPhone);
        List<CarpUser> workUsers = workUserMapper.selectByMap(map);

        if (workUsers.isEmpty()){
            throw new ServiceException(401,"用户不存在,请重新登录!");
        }

        //用户密码加签 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(workUsers.get(0).getPassword())).build();
        try{
            jwtVerifier.verify(token);
        }catch (Exception e){
            throw new ServiceException(401,"token验证失败,请重新登录!");
        }

        return true;
    }
}
